package ksv.cron.v1;

import lombok.Getter;
import lombok.Setter;
import org.springframework.scheduling.support.CronSequenceGenerator;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @创建人 xiaojiancheng
 * @时间 2020/8/15
 * @描述 定时任务表达式对应的 解析
 */
@Setter
@Getter
public class CronHandler {
    private String expression;
    private String eventName;
    private Integer second = 0;
    //  如果超时了  是否强制执行
    private boolean forceExecute = false;
    private CronSequenceGenerator cronSequenceGenerator;

    public CronHandler(String expression, String eventName) {
        this.expression = expression;
        this.eventName = eventName;

        cronSequenceGenerator = new CronSequenceGenerator(expression);
    }

    public LocalDateTime next(){
        return next(LocalDateTime.now());
    }

    public LocalDateTime next(LocalDateTime current){
        //  注意 这里月份需要减少1
        Calendar calendar = new GregorianCalendar(current.getYear(),current.getMonthValue() -1,current.getDayOfMonth(),current.getHour(),current.getMinute(),current.getSecond());

        Date date = calendar.getTime();
        Date next = cronSequenceGenerator.next(date);
        if(next == null){
            return null;
        }

        Instant instant = next.toInstant();
        LocalDateTime rtn = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).plusSeconds(second);

        //  超过360天视为无效
        if(Duration.between(current,rtn).getSeconds() > 360 * 24 * 60 * 60l){
            return null;
        }
        return rtn;
    }

}
